package com.eight.config;

import com.alibaba.fastjson2.JSON;
import com.eight.controller.AdminLogin;
import com.eight.service.UserService;
import com.eight.util.JWTTool;
import com.eight.vo.ComResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.annotation.Resource;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Description: springSecurity的配置类
 * @Author: Van.Planifolia
 * @CreateTime: 2023-02-22  21:18
 * @Version: 1.0
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource(name = "userService")
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private AdminLogin adminLogin;
    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置登录后的成功回调处理器与失败回调处理器
        http.formLogin()
                // 设置自定义表单地提交路径
                .loginProcessingUrl("/login")
                // 登录成功之后的处理器对象
                .successHandler(successHandler())
                // 登录失败的处理器对象
                .failureHandler(failureHandler())
                // 上面的这些内容允许全部的用户访问
                .permitAll();
        http.authorizeRequests()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/upload/**").permitAll()

        ;
        // 设置跨域与拦截其他请求
        http.cors();
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
        http.sessionManagement()
                // 设置 Session 会话失效时重定向路径，默认为 loginPage()
                // .invalidSessionUrl("/login")
                // 配置使用自定义的 Session 会话失效处理策略
                //.invalidSessionStrategy(invalidSessionStrategy)
                // 设置单用户的 Session 最大并发会话数量，-1 表示不受限制
                .maximumSessions(1)
                // 设置为 true，表示某用户达到最大会话并发数后，新会话请求会被拒绝登录
                .maxSessionsPreventsLogin(false)
                // 设置所要使用的 sessionRegistry，默认为 SessionRegistryImpl 实现类
                .sessionRegistry(sessionRegistry);

    }

    private AuthenticationFailureHandler failureHandler() {
        return ((request, response, e) -> {
            // 设置编码格式
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            String fail = JSON.toJSONString(new ComResult(5001, "登录失败sc", e.getMessage()));
            try {
                adminLogin.loginAop(0, null);
            }catch (Exception ignored){
            }
            writer.println(fail);
            writer.flush();
            writer.close();
        });
    }

    /**
     * 登录成功的处理器方法
     *
     * @return 成功处理器
     */
    private AuthenticationSuccessHandler successHandler() {
        // 这里成功之后我们要生产token并且将token存入到redis中
        return ((request, response, authentication) -> {
            // 设置编码格式
            response.setContentType("application/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            // 拿到用户的信息
            User user = (User) authentication.getPrincipal();
            String username = user.getUsername();
            List<String> permissions = authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
            // 生产token
            Map<String, Object> map = new HashMap<>();
            map.put("username", username);
            map.put("permissions", permissions);
            String token = JWTTool.generateToken(map);
            // 将token返回给前端并且存入雷迪斯中
            redisTemplate.opsForValue().set(token, "", 30, TimeUnit.DAYS);
            ComResult comResult = new ComResult(2000, "登录成功", token);
            String json = JSON.toJSONString(comResult);
            try {
                adminLogin.loginAop(1, token);
            }catch (Exception ignored){
            }
            // 推送json
            writer.println(json);
            writer.flush();
            writer.close();
        });
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用本地自自定义的用户加载类,并且使用bCryptPasswordEncoder密码加密器
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);

    }


}
